package com.franklin.ideaplugin.api.ui.editor;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.franklin.ideaplugin.api.collection.map.RecursionMap;
import com.franklin.ideaplugin.api.icon.ApiIcons;
import com.franklin.ideaplugin.api.ui.IBaseComponent;
import com.franklin.ideaplugin.api.utils.PsiUtil;
import com.google.common.collect.Maps;
import com.intellij.psi.PsiType;

import javax.swing.*;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

/**
 * @author Ye Junhui
 * @since 2023/7/12
 */
public interface IBaseResetEditor extends IBaseComponent {

    /**
     * 初始化重置参数按钮
     * @param customEditor
     * @param resetBtn
     */
    default void initRestButton(CustomEditor customEditor, JButton resetBtn){
        resetBtn.setIcon(ApiIcons.REFRESH_ICON);
        resetBtn.setText("Reset parameter value with default value");
        resetBtn.setToolTipText("Reset parameter value with default value");
        resetBtn.addActionListener(e -> {
            PsiType psiType = customEditor.getPsiType();
            if (Objects.isNull(psiType)){
                return;
            }
            Object defaultValueOfPsiType = PsiUtil.getDefaultValueOfPsiType(psiType, new RecursionMap<>());
            if (Objects.isNull(defaultValueOfPsiType)){
                return;
            }
            if (defaultValueOfPsiType instanceof Map || defaultValueOfPsiType instanceof Collection){
                customEditor.setText(JSON.toJSONString(defaultValueOfPsiType, JSONWriter.Feature.PrettyFormat),CustomEditor.JSON_FILE_TYPE);
            }else {
                customEditor.setText(String.valueOf(defaultValueOfPsiType));
            }
        });
    }
}
